var knex = require('../dbhelper').instance();
var Promise = require('bluebird');
module.exports = {
    getlist: function (condition) {
        return new Promise(function (resolve, reject) {
            knex.transaction(function (trx) {
                var promiseArray = [];
                if (condition.isfull) {
                    if (typeof (condition.key) == 'string' || (condition.key.taskname.length == 0 && condition.key.start.length == 0 && condition.key.end.length == 0)) {
                        promiseArray.push(knex('tasklist')
                            .select('*').limit(condition.limit).offset((condition.page - 1) * condition.limit).orderBy('createat', 'desc').transacting(trx));
                        promiseArray.push(knex('tasklist')
                            .select(knex.raw('count(1) as total')).transacting(trx));
                    } else {
                        condition.key.start = condition.key.start || '2000-01-01 00:00:00';
                        condition.key.end = condition.key.end || '3000-01-01 00:00:00';
                        promiseArray.push(knex('tasklist').where('taskname', 'like', '%' + condition.key.taskname + '%').whereBetween('createat', [condition.key.start, condition.key.end])
                            .select('*').limit(condition.limit).offset((condition.page - 1) * condition.limit).orderBy('createat', 'desc').transacting(trx));
                        promiseArray.push(knex('tasklist').where('taskname', 'like', '%' + condition.key.taskname + '%').whereBetween('createat', [condition.key.start, condition.key.end])
                            .select(knex.raw('count(1) as total')).transacting(trx));
                    }
                } else {
                    if (typeof (condition.key) == 'string' || (condition.key.taskname.length == 0 && condition.key.start.length == 0 && condition.key.end.length == 0)) {
                        promiseArray.push(knex('tasklist').where('userid', condition.userid)
                            .select('*').limit(condition.limit).offset((condition.page - 1) * condition.limit).orderBy('createat', 'desc').transacting(trx));
                        promiseArray.push(knex('tasklist')
                            .select(knex.raw('count(1) as total')).transacting(trx));
                    } else {
                        condition.key.start = condition.key.start || '2000-01-01 00:00:00';
                        condition.key.end = condition.key.end || '3000-01-01 00:00:00';
                        promiseArray.push(knex('tasklist').where('taskname', 'like', '%' + condition.key.taskname + '%').andWhere('userid', condition.userid).whereBetween('createat', [condition.key.start, condition.key.end])
                            .select('*').limit(condition.limit).offset((condition.page - 1) * condition.limit).orderBy('createat', 'desc').transacting(trx));
                        promiseArray.push(knex('tasklist').where('taskname', 'like', '%' + condition.key.taskname + '%').whereBetween('createat', [condition.key.start, condition.key.end])
                            .select(knex.raw('count(1) as total')).transacting(trx));
                    }
                }
                return Promise.all(promiseArray)
                    .then(trx.commit)
                    .catch(trx.rollback);
            }).then(function (resp) {
                resolve(resp);
            }).catch(function (err) {
                console.error(err);
            });
        });
    },
    addfolder: function (params) {
        return new Promise(function (resolve, reject) {
            knex('folder').insert(params).then(function (data) {
                resolve(data);
            }).catch(function (error) {
                console.error(error);
                reject(error);
            });
        });
    },
    addresource: function (params) {
        return new Promise(function (resolve, reject) {
            knex('resource').insert(params).then(function (data) {
                resolve(data);
            }).catch(function (error) {
                console.error(error);
                reject(error);
            });
        });
    },
    addresource: function (params) {
        return new Promise(function (resolve, reject) {
            knex('resource').insert(params).then(function (data) {
                resolve(data);
            }).catch(function (error) {
                console.error(error);
                reject(error);
            });
        });
    },
    resourcelist: function (condition) {
        return new Promise(function (resolve, reject) {
            knex.transaction(function (trx) {
                return Promise.all([
                        knex('resource').leftJoin('folder', 'resource.folderid', 'folder.folderid').where('folder.folderid', '=', knex.raw('?', [condition.folderid]))
                        .select('resource.*', 'folder.foldername', 'folder.path').limit(condition.limit).offset((condition.page - 1) * condition.limit).orderBy('createat', 'desc').transacting(trx),

                        knex('resource').leftJoin('folder', 'resource.folderid', 'folder.folderid').where('folder.folderid', '=', knex.raw('?', [condition.folderid]))
                        .select(knex.raw('count(1) as total')).transacting(trx)
                    ])
                    .then(trx.commit)
                    .catch(trx.rollback);
            }).then(function (resp) {
                resolve(resp);
            }).catch(function (err) {
                console.error(err);
            });
        });
    },
    addtask: function (task_params, flowconfig_params, dslist_params) {
        return new Promise(function (resolve, reject) {
            knex.transaction(function (trx) {
                return Promise.all([
                        //对数据集进行副本复制
                        knex.raw('call proc_task_dscopy(?,?)', ['dstable_' + dslist_params.dsid, 'dstable_' + dslist_params.inputdsids]).transacting(trx),
                        knex('dslist').insert(dslist_params).transacting(trx),
                        knex('flowconfig').insert(flowconfig_params).transacting(trx),
                        knex('tasklist').insert(task_params).transacting(trx),
                        knex('dslist').update({
                            'totalcount': knex.raw('(select count(1) from ??)', ['dstable_' + dslist_params.dsid])
                        }).where('dstable', 'dstable_' + dslist_params.dsid).transacting(trx),
                    ])
                    .then(trx.commit)
                    .catch(trx.rollback);
            }).then(function (resp) {
                resolve(resp);
            }).catch(function (err) {
                console.error(err);
                reject(err);
            });
        });
    },
    getbaseinfo: function (taskid) {
        return new Promise(function (resolve, reject) {
            knex('tasklist').where('taskid', taskid).select('*').then(function (data) {
                resolve(data);
            }).catch(function (error) {
                console.error(error);
                reject(error);
            });
        });
    },
    update: function (params, taskid, dsid) {
        return new Promise(function (resolve, reject) {
            var promiseArray = [];

            knex.transaction(function (trx) {
                promiseArray.push(knex('tasklist').update(params).where('taskid', taskid).transacting(trx));
                if (params.actions==undefined) {
                    promiseArray.push(knex('dslist').update({'status':1}).where('dsid', dsid).transacting(trx));
                }else{
                    promiseArray.push(knex('dslist').update({'actions':params.actions,"dstags":params.tasktags}).where(knex.raw('dsid=(select dsid from tasklist where taskid=?)',[taskid])).transacting(trx));
                }
                return Promise.all(promiseArray)
                    .then(trx.commit)
                    .catch(trx.rollback);
            }).then(function (resp) {
                resolve(resp);
            }).catch(function (err) {
                console.error(err);
            });
        });
    },
    getflowinfo: function (configid) {
        return new Promise(function (resolve, reject) {
            knex.transaction(function (trx) {
                return Promise.all([
                        knex('flowconfig').where('configid', configid).select('*').transacting(trx),
                        knex('users').whereRaw('FIND_IN_SET(userid,(select concat(markusers,\',\',inspectusers,\',\',rndinspectusers,\',\',acceptusers) from flowconfig where configid=?))', [configid]).select('*').transacting(trx)
                    ])
                    .then(trx.commit)
                    .catch(trx.rollback);
            }).then(function (resp) {
                resolve(resp);
            }).catch(function (err) {
                console.error(err);
            });
        });
    },
    updateflow: function (params, configid) {
        return new Promise(function (resolve, reject) {
            knex('flowconfig').update(params).where('configid', configid).then(function (data) {
                resolve(data);
            }).catch(function (error) {
                console.error(error);
                reject(error);
            });
        });
    },
    getactionlist: function (condition) {
        return new Promise(function (resolve, reject) {
            knex.transaction(function (trx) {
                var promiseArray = [];

                promiseArray.push(knex('tasklist')
                    .leftJoin('flowconfig', 'tasklist.configid', 'flowconfig.configid')
                    .leftJoin('dslist', 'dslist.dsid', 'tasklist.dsid')
                    .leftJoin('users', 'users.userid', 'tasklist.userid')
                    .whereRaw('FIND_IN_SET(?,??) and (tasklist.status=0 or tasklist.status=1)', [condition.userid, 'flowconfig.' + condition.action])
                    .andWhere('tasklist.status', '1')
                    .orderBy('tasklist.createat', 'desc')
                    .select('tasklist.*', 'users.username', 'dslist.totalcount', 'dslist.dstable')
                    .transacting(trx));

                promiseArray.push(knex('tasklist')
                    .leftJoin('flowconfig', 'tasklist.configid', 'flowconfig.configid')
                    .whereRaw('FIND_IN_SET(?,??) and (tasklist.status=0 or tasklist.status=1)', [condition.userid, 'flowconfig.' + condition.action])
                    .select(knex.raw('count(1) as total'))
                    .transacting(trx));

                return Promise.all(promiseArray)
                    .then(trx.commit)
                    .catch(trx.rollback);
            }).then(function (resp) {
                resolve(resp);
            }).catch(function (err) {
                console.error(err);
            });
        });
    },
    //获取任务的状态
    gettaskstatus: function (taskid) {
        return new Promise(function (resolve, reject) {
            knex('tasklist').select('status').where('taskid', taskid).then(function (data) {
                resolve(data);
            }).catch(function (error) {
                console.error(error);
                reject(error);
            });
        });
    },
    //指定用户参与过的任务列表
    partake_list: function (condition) {
        return new Promise(function (resolve, reject) {
            knex.transaction(function (trx) {
                var promiseArray = [];
                var subquery = knex('flowconfig').
                select('configid')
                .where(knex.raw('find_in_set(?,markusers)', [condition.userid]))
                .orWhere(knex.raw('find_in_set(?,inspectusers)', [condition.userid]))
                .orWhere(knex.raw('find_in_set(?,rndinspectusers)', [condition.userid]))
                .orWhere(knex.raw('find_in_set(?,acceptusers)', [condition.userid]));
                if (typeof (condition.key) == 'string' || (condition.key.taskname.length == 0 && condition.key.start.length == 0 && condition.key.end.length == 0)) {
                    promiseArray.push(knex('tasklist').whereIn('configid', subquery)
                        .select('*').limit(condition.limit).offset((condition.page - 1) * condition.limit).orderBy('createat', 'desc').transacting(trx));
                    promiseArray.push(knex('tasklist').whereIn('configid', subquery)
                        .select(knex.raw('count(1) as total')).transacting(trx));
                } else {
                    condition.key.start = condition.key.start || '2000-01-01 00:00:00';
                    condition.key.end = condition.key.end || '3000-01-01 00:00:00';
                    promiseArray.push(knex('tasklist')
                        .whereIn('configid', subquery)
                        .andWhere('taskname', 'like', '%' + condition.key.taskname + '%')
                        .whereBetween('createat', [condition.key.start, condition.key.end])
                        .select('*').limit(condition.limit).offset((condition.page - 1) * condition.limit).orderBy('createat', 'desc').transacting(trx));

                    promiseArray.push(knex('tasklist')
                        .whereIn('configid', subquery)
                        .andWhere('taskname', 'like', '%' + condition.key.taskname + '%')
                        .whereBetween('createat', [condition.key.start, condition.key.end])
                        .select(knex.raw('count(1) as total')).transacting(trx));
                }

                return Promise.all(promiseArray)
                    .then(trx.commit)
                    .catch(trx.rollback);
            }).then(function (resp) {
                resolve(resp);
            }).catch(function (err) {
                console.error(err);
                reject(err);
            });
        });
    }
};